package com.example.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 请求日志过滤器
 * 功能：性能监控、业务分析、安全审计
 */
@Component
@Order(0)  // 优先级最高，最先执行
public class LoggingFilter implements Filter {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 请求计数器（用于业务分析）
    private static final AtomicLong REQUEST_COUNTER = new AtomicLong(0);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("📝 LoggingFilter 已初始化 - 开始记录系统日志");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 生成请求ID（用于追踪）
        long requestId = REQUEST_COUNTER.incrementAndGet();
        String requestTime = LocalDateTime.now().format(FORMATTER);
        
        // 🎯 1. 基本请求信息收集
        String method = httpRequest.getMethod();
        String uri = httpRequest.getRequestURI();
        String clientIP = getClientIP(httpRequest);
        String userAgent = httpRequest.getHeader("User-Agent");
        
        // 🎯 2. 性能监控 - 开始计时
        long startTime = System.currentTimeMillis();
        
        // 🎯 3. 安全审计 - 登录尝试检测
        boolean isLoginAttempt = uri.contains("/login");
        if (isLoginAttempt) {
            logSecurityEvent("LOGIN_ATTEMPT", requestId, clientIP, userAgent, requestTime);
        }
        
        System.out.printf("📥 [%d] %s %s %s - %s%n", 
            requestId, requestTime, method, uri, clientIP);
        
        try {
            // 继续执行请求
            chain.doFilter(request, response);
            
        } finally {
            // 🎯 4. 性能监控 - 计算耗时
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            int statusCode = httpResponse.getStatus();
            
            // 🎯 5. 记录完整的请求日志
            logRequestComplete(requestId, method, uri, clientIP, duration, statusCode, requestTime);
            
            // 🎯 6. 安全审计 - 登录结果检测
            if (isLoginAttempt) {
                logLoginResult(requestId, clientIP, statusCode, duration, requestTime);
            }
            
            // 🎯 7. 业务分析 - API使用统计
            logApiUsage(uri, method, duration, statusCode);
        }
    }
    
    /**
     * 获取客户端真实IP
     */
    private String getClientIP(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIP = request.getHeader("X-Real-IP");
        if (xRealIP != null && !xRealIP.isEmpty()) {
            return xRealIP;
        }
        
        return request.getRemoteAddr();
    }
    
    /**
     * 🛡️ 安全审计 - 记录安全事件
     */
    private void logSecurityEvent(String eventType, long requestId, String clientIP, 
                                 String userAgent, String time) {
        System.out.printf("🛡️  [SECURITY] [%d] %s %s - IP:%s UA:%s%n", 
            requestId, time, eventType, clientIP, 
            userAgent != null ? userAgent.substring(0, Math.min(userAgent.length(), 50)) + "..." : "Unknown");
    }
    
    /**
     * 📊 性能监控 - 记录请求完成信息
     */
    private void logRequestComplete(long requestId, String method, String uri, 
                                  String clientIP, long duration, int statusCode, String time) {
        String performanceLevel = getPerformanceLevel(duration);
        
        System.out.printf("📤 [%d] %s %s %s %s - %dms [%d] %s%n", 
            requestId, time, method, uri, clientIP, duration, statusCode, performanceLevel);
    }
    
    /**
     * 🔒 安全审计 - 记录登录结果
     */
    private void logLoginResult(long requestId, String clientIP, int statusCode, 
                               long duration, String time) {
        if (statusCode == 200) {
            System.out.printf("✅ [LOGIN_SUCCESS] [%d] %s - IP:%s 登录成功 (%dms)%n", 
                requestId, time, clientIP, duration);
        } else if (statusCode == 401) {
            System.out.printf("❌ [LOGIN_FAILED] [%d] %s - IP:%s 登录失败 (%dms) ⚠️ 可能的暴力破解尝试%n", 
                requestId, time, clientIP, duration);
        }
    }
    
    /**
     * 📈 业务分析 - API使用统计
     */
    private void logApiUsage(String uri, String method, long duration, int statusCode) {
        // 简化的统计（实际项目中可以用Redis或数据库存储）
        if (REQUEST_COUNTER.get() % 10 == 0) {  // 每10个请求输出一次统计
            System.out.printf("📊 [STATS] 总请求数: %d, 当前API: %s %s%n", 
                REQUEST_COUNTER.get(), method, uri);
        }
        
        // 慢查询告警
        if (duration > 1000) {
            System.out.printf("🐌 [SLOW_QUERY] %s %s - %dms (>1000ms 需要优化!)%n", 
                method, uri, duration);
        }
    }
    
    /**
     * 性能等级评估
     */
    private String getPerformanceLevel(long duration) {
        if (duration < 100) return "🚀 FAST";
        else if (duration < 500) return "✅ NORMAL"; 
        else if (duration < 1000) return "⚠️ SLOW";
        else return "🐌 VERY_SLOW";
    }

    @Override
    public void destroy() {
        System.out.println("📝 LoggingFilter 已销毁");
    }
}
